package org.hermes.core{
	import com.adobe.serialization.json.JSON;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	
	import org.hermes.core.message.MessagePopUp;
	import org.hermes.core.message.MessageUtil;
	
	
	public class ServiceCall{
		private static const STATUS_OK:Number = 1;
		private static const STATUS_EXCEPTION:Number = 2;
		
		public static const TYPE_MSG_WARNING:Number = 1;
		public static const TYPE_MSG_INFO:Number = 2;
		public static const TYPE_MSG_ERROR:Number = 3;
		public static const TYPE_MSG_QUESTION:Number = 4;
		
		
		
		public static function call(serviceRequest:String, requestData:Object = null, callLater:Function = null, callLaterException:Function = null, callLaterMessages:Function = null):void{
			try{
				//var brokerURL:String = HTMLParameters.getBrokerURL();
				
				var urlLoader:URLLoader = new URLLoader();
				//var urlRequest:URLRequest = new URLRequest(brokerURL + "/" + serviceRequest + ".sbr");
				var urlRequest:URLRequest = new URLRequest(serviceRequest + ".sbr");
				
				urlRequest.method = "POST";
				urlRequest.data = JSON.encode(requestData);
				
				urlLoader.addEventListener(Event.COMPLETE, function(event:Event):void{
					var response:URLLoader = URLLoader(event.target);
					var serviceResponse:Object = JSON.decode(response.data);
					
					if(serviceResponse["status"] == STATUS_OK){
						var serviceMessages:Array = serviceResponse["serviceMessages"] as Array;
						
						if(serviceMessages != null && serviceMessages.length > 0){
							if(callLaterMessages != null){
								callLaterMessages(serviceMessages);
							}else{
								showMessages(serviceMessages);
							}
						}
						
						if(callLater != null && serviceResponse.hasOwnProperty("responseData")){
							callLater(serviceResponse["responseData"]);
						}
					}else if(serviceResponse["status"] == STATUS_EXCEPTION){
						var serviceExceptions:Array = serviceResponse["serviceMessages"] as Array;
						
						if(callLaterException != null){
							callLaterException(serviceExceptions);
						}else{
							MessageUtil.showError("Erro!", serviceExceptions[0].message);
						}
					}else{
						throw new Error("Service Response with status unknown.");
					}
				});
				
				urlLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{
					var error:String = "Error to invoke service, maybe do you not started your server or not exist service mappeds.";
					Alert.show(error + "\n\n" + e.text, "Erro!");
					trace(e.text);	
				});
					
				urlLoader.load(urlRequest);
			}catch(e:Error){
				Alert.show(e.message, "Erro!");
				trace(e.getStackTrace());
			}
		}
		
		private static function showMessages(messages:Array):void{
			if(messages.length == 1){
				if( messages[0].type == TYPE_MSG_INFO){
					MessageUtil.showInfo("Informação", messages[0].message);
				}else if(messages[0].type == TYPE_MSG_ERROR){
					MessageUtil.showError("Erro!", messages[0].message);
				}else{
					MessageUtil.showWarning("Aviso", messages[0].message);
				} 
			}else{
				var msgPopUp:MessagePopUp = new MessagePopUp();
				msgPopUp.dataProvider = new ArrayCollection(messages);
				
				PopUpManager.addPopUp(msgPopUp, (Application.application as DisplayObject));
				PopUpManager.centerPopUp(msgPopUp);
			}
		}
	}
}